const schedule = require('node-schedule')

const { spawn } = require('child_process')
let child = null
let output = ''

const date = new Date(2018, 5, 27, 8, 56, 0)

schedule.scheduleJob(date, () => {
  module.exports.start()
})

exports.start = async ctx => {
  if (new Date().getTime() < date.getTime()) {
    ctx.body = `任务未开始，计划时间：${date.toLocaleString()}`
    return
  }

  if (child) {
    return (ctx.body = '-----> Already started cnzz process <-----')
  }

  child = spawn('node', ['src/cnzz'], {
    cwd: process.cwd()
  })

  child.stdout.on('data', data => {
    let temp = output.split('\n')
    if (temp.length > 30) {
      temp = temp.slice(-30)
    }
    output = temp.join('\n')
    output += data.toString()
  })

  child.stderr.on('data', data => {
    console.log(`stderr: ${data}`)
  })

  child.on('error', error => {
    console.log('​error', error)
  })

  child.on('close', code => {
    console.log(`child process exited with code ${code}`)
  })

  if (ctx) {
    ctx.body = 'ojbk, process will start soon'
  }
}

exports.stop = async ctx => {
  if (!child) {
    ctx.body = 'No process runing'
    return
  }
  child.kill()
  child = null
  output = ''
  ctx.body = '结束成功'
}

exports.getLog = async ctx => {
  if (new Date().getTime() < date.getTime()) {
    ctx.body = `任务未开始，计划时间：${date.toLocaleString()}`
    return
  }

  if (!child) {
    console.log('xxxx')
    await module.exports.start(ctx)
    ctx.body = 'Start cnzz'
    return
  }

  ctx.body = output
}
